import Chat from "@/model/Chat"
import ChatAPI from "@/views/chat/ChatAPI"

export default {
  namespaced: true,
  state: {
    chats: [],
  },
  mutations: {
    setChats(state: any, chats: Chat[]) {
      state.chats = chats
    },
    pushChat(state: any, newChat: Chat) {
      //如果列表中已经包含次chat
      //则找到chat，赋值,加入新message
      //在列表中将这个chat放到最前面
      const chatIndex = state.chats.findIndex((chatItem: any) => chatItem.id === newChat.id)
      let chat: Chat = null
      //如果已经存在和此人的聊天记录了
      if (chatIndex >= 0) {
        chat = state.chats[chatIndex]
        chat.messages.push(...newChat.messages)
        state.chats.splice(chatIndex, 1)
      } else {
        chat = newChat
      }
      state.chats.unshift(chat)
    }
  },
  actions: {
    getChats({commit}) {
      return ChatAPI.getChatsAPI().then(res => {
        commit('setChats', res.data)
      })
    }
  }
}
